import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;

class MyClassLoader extends URLClassLoader {
    public MyClassLoader(URL[] urls) {
        super(urls);
    }

    public Class<?> loadClass(String name) throws ClassNotFoundException {
        synchronized (getClassLoadingLock(name)) {
            Class<?> c = findLoadedClass(name);
            if (c == null) {
                try {
                    c = findClass(name);
                } catch (ClassNotFoundException e) {

                }
                if (c == null) {
                    if (getParent() != null) {
                        c = getParent().loadClass(name);
                    }
                }
            }
            return c;
        }
    }
}

public class JniLoader {
    public static void main(String[] args) throws Exception
    {
        File file = new File("./libhello.jar");
        URL url = file.toURI().toURL();

        MyClassLoader loader = new MyClassLoader(new URL[]{url});
        Class<?> aClass = loader.loadClass("HelloWorld");
        System.out.println(aClass);
        Object helloWorld = aClass.getDeclaredConstructor().newInstance();
        aClass.getMethod("sayHello").invoke(helloWorld);

        // 不同ClassLoader会加载到不同的地址空间，静态变量不会冲突，cnt计数不影响
        MyClassLoader loader2 = new MyClassLoader(new URL[]{url});
        Class<?> aClass2 = loader2.loadClass("HelloWorld");
        Object helloWorld2 = aClass2.getDeclaredConstructor().newInstance();
        aClass2.getMethod("sayHello").invoke(helloWorld2);

        loader.close();
        loader2.close();
    }
}
